package cn.edu.ldu.views.modules.controller;

import cn.edu.ldu.modules.entity.TokenEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.modules.entity.UserEntity;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.util.Translate;

import javax.swing.tree.TreeNode;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

public class UserController {

    private static DatagramSocket serverSocket;
    private static HashMap<Long, TokenEntity> userList = new HashMap<>();

    public static DatagramSocket getServerSocket() {
        try {
            return serverSocket != null ? serverSocket : (serverSocket = new DatagramSocket(Consts.port));
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HashMap<Long, TokenEntity> getUserList() {
        return userList;
    }

    public static void addUserToList(TokenEntity tokenEntity) {
        userList.put(tokenEntity.getUserId(), tokenEntity);
    }

    public static void removeUserToList(Long userId) {
        userList.remove(userId);
    }

    public static boolean sendDataToUser(Long userId, Protocol protocol) throws IOException{
        if(userList.get(userId) != null){
            protocol.setPacket(null);
            protocol.setToken(null);
            byte[] data = Translate.ObjectToByte(protocol);
            DatagramPacket newPacket = new DatagramPacket(data, data.length, userList.get(userId).getAddress(), userList.get(userId).getPort());
            serverSocket.send(newPacket);
            L.OK(protocol.getKey(), UserController.class);
            L.OK(newPacket, UserController.class, 1);
            return true;
        }
        return false;
    }

    public static void sendMsgToUser(Protocol protocol) throws IOException{
        sendDataToUser(protocol);
    }

    public static void sendDataToUser(Protocol protocol) throws IOException{
        InetAddress inetAddress = protocol.getPacket().getAddress();
        int port = protocol.getPacket().getPort();
        protocol.setPacket(null);
        byte[] data = Translate.ObjectToByte(protocol);
        DatagramPacket newPacket = new DatagramPacket(data, data.length, inetAddress, port);
        L.OK(protocol.getKey(),UserController.class);
        L.OK(newPacket, UserController.class, 1);
        serverSocket.send(newPacket);
    }

}
